<?php
/**
 * Created by PhpStorm.
 * User: daimingkang
 * Date: 2018/8/7
 * Time: 上午11:38
 */

namespace App\Api\Controllers\Tfpay;


use App\Api\Controllers\BaseController;
use App\Api\Controllers\Config\TfConfigController;
use App\Common\PaySuccessAction;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Store;
use App\Models\StorePayWay;
use App\Models\TfStore;
use App\Models\UserRate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use MyBank\Tools;

class NotifyController extends BaseController
{

    public function store_notify(Request $request)
    {

        try {


            $data = $request->all();
            //成功
            if ($data['status'] == 1 || $data['status'] == 4) {
                $TfStore = TfStore::where('agent_id', $data['agent_id'])
                    ->where('sub_mch_id', $data['sub_mch_id'])
                    ->first();

                if ($TfStore) {

                    if ($data['status'] == 1) {

                        $data_up = [
                            'status' => 1,
                            'status_desc' => '审核成功',
                        ];
                        $config_id = $TfStore->config_id;
                        $store_id = $TfStore->store_id;
                        $config = new TfConfigController();
                        $tf_config = $config->tf_config($config_id, $TfStore->qd);
                        if (!$tf_config) {
                            return '';
                        }

                        $Store = Store::where('store_id', $store_id)
                            ->select('user_id')
                            ->first();

                        if (!$Store) {
                            return '';
                        }

                        //费率 默认商户的费率为代理商的费率
                        $UserRate = UserRate::where('user_id', $Store->user_id)
                            ->where('ways_type', '12001')//目前是一样的直接读取支付宝就行
                            ->first();
                        $rate = 0.6;
                        if ($UserRate) {
                            $rate = $UserRate->store_all_rate;
                        }


                        //查找是否有此通道
                        $ways1 = StorePayWay::where('store_id', $store_id)
                            ->where('ways_type', '12001')
                            ->select('rate')
                            ->first();
                        if ($ways1) {
                            $rate = $ways1->rate;//如果门店设置走门店扫码费率

                        }

                        //传化报备

                        $obj = new \App\Api\Controllers\Tfpay\BaseController();
                        $obj->mch_id = $tf_config->mch_id;
                        $obj->pub_key = $tf_config->pub_key;
                        $obj->pri_key = $tf_config->pri_key;


                        $sub_mch_id = $data['sub_mch_id'];


                        //签署电子合同
                        $post_data = [
                            'sub_mch_id' => $sub_mch_id,
                        ];

                        $method = '/openapi/merchant/contract';
                        $re = $obj->api($post_data, $method, false);


                        //费率同步

                        $rate1 = $rate * 10;
                        $post_data = [
                            'sub_mch_id' => $sub_mch_id,
                            'WECHAT_POS' => $rate1,
                            'WECHAT_SCAN' => $rate1,
                            'WECHAT_MP' => $rate1,
                            'ALIPAY_POS' => $rate1,
                            'ALIPAY_SCAN' => $rate1,
                            'ALIPAY_MP' => $rate1,
                        ];

                        $method = '/openapi/merchant/rate';
                        $re = $obj->api($post_data, $method, false);

                        if ($re['code'] != 0) {

                            return '';
                        }

                        //新增app ID
                        $post_data = [
                            'sub_mch_id' => $data['sub_mch_id'],
                            'sub_appid' => $tf_config->wx_appid,
                        ];
                        $method = '/openapi/merchant/wechat/appid';
                        $appid = $obj->api($post_data, $method, false);


                        //报备支付授权目录
                        $post_data = [
                            'sub_mch_id' => $data['sub_mch_id'],
                            'jsapi_path' => env('APP_URL') . '/api/tfpay/weixin/',
                        ];
                        $method = '/openapi/merchant/wechat/jsapi-path';
                        $jsapipath = $obj->api($post_data, $method, false);


                    } else {
                        $data_up = [
                            'status' => 3,
                            'status_desc' => $data['remark'],
                        ];
                    }


                    StorePayWay::where('store_id', $TfStore->store_id)
                        ->where('company', 'tfpay')
                        ->update($data_up);
                }


            }


        } catch (\Exception $exception) {
            Log::info('传化门店审核异步');
            Log::info($exception);
        }

    }


    public function notify_url(Request $request)
    {

        try {
            $data = $request->all();
            if (isset($data['out_trade_no'])) {
                $out_trade_no = $data['out_trade_no'];
                $day = date('Ymd', time());
                $table = 'orders_' . $day;
                if (Schema::hasTable($table)) {
                    $order = DB::table($table)->where('out_trade_no', $out_trade_no)->first();

                } else {
                    $order = Order::where('out_trade_no', $out_trade_no)->first();
                }

                //订单存在
                if ($order) {
                    //三方订单状态成功
                    if ($data['trade_status'] == '1') {
                        //系统订单未成功
                        if ($order->pay_status == 2) {
                            $trade_no = $data['channel_no'];
                            $pay_time = $data['paid_at'];
                            $buyer_pay_amount = $data['total_fee'];
                            $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
                            $buyer_id = $data['user_info'];
                            $in_data = [
                                'status' => '1',
                                'pay_status' => 1,
                                'pay_status_desc' => '支付成功',
                                'trade_no' => $trade_no,
                                'pay_time' => $pay_time,
                                'buyer_id' => $buyer_id,
                                'buyer_pay_amount' => $buyer_pay_amount,
                            ];

                          $this->update_day_order($in_data,$out_trade_no);


                            if (strpos($out_trade_no, 'scan')) {


                            } else {
                                //支付成功后的动作
                                $data = [
                                    'ways_type' => $order->ways_type,
                                    'company' => $order->company,
                                    'ways_type_desc' => $order->ways_type_desc,
                                    'source_type' => '12000',//返佣来源
                                    'source_desc' => 'TF',//返佣来源说明
                                    'total_amount' => $order->total_amount,
                                    'out_trade_no' => $order->out_trade_no,
                                    'other_no' => $order->other_no,
                                    'rate' => $order->rate,
                                    'fee_amount' => $order->fee_amount,
                                    'merchant_id' => $order->merchant_id,
                                    'store_id' => $order->store_id,
                                    'user_id' => $order->user_id,
                                    'config_id' => $order->config_id,
                                    'store_name' => $order->store_name,
                                    'ways_source' => $order->ways_source,
                                    'pay_time' => $pay_time,
                                    'device_id' => $order->device_id,
                                ];

                                PaySuccessAction::action($data);

                            }


                        } else {
                            //系统订单已经成功了
                        }
                    }


                } else {


                }

            }

            return 'SUCCESS';

        } catch (\Exception $exception) {
            Log::info('传化异步报错');
            Log::info($exception);

        }
    }
}